<template>
  <div class="contact-form-container">
    <el-form
      ref="contactFormRef"
      :model="contactForm"
      :rules="contactRules"
      label-width="80px"
      class="contact-form"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="contactForm.name" placeholder="请输入联系人姓名" />
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="contactForm.sex">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
          <el-radio :label="0">未知</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="手机号码" prop="mobile">
        <el-input v-model="contactForm.mobile" placeholder="请输入联系人手机号码" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="contactForm.email" placeholder="请输入联系人邮箱" />
      </el-form-item>

      <el-form-item label="微信" prop="wechat">
        <el-input v-model="contactForm.wechat" placeholder="请输入联系人微信" />
      </el-form-item>

      <el-form-item label="QQ" prop="qq">
        <el-input v-model="contactForm.qq" placeholder="请输入联系人QQ" />
      </el-form-item>

      <el-form-item label="称谓" prop="nickname">
        <el-input v-model="contactForm.nickname" placeholder="请输入联系人称谓" />
      </el-form-item>

      <el-form-item label="部门" prop="department">
        <el-input v-model="contactForm.department" placeholder="请输入联系人部门" />
      </el-form-item>

      <el-form-item label="职务" prop="position">
        <el-input v-model="contactForm.position" placeholder="请输入联系人职务" />
      </el-form-item>

      <el-form-item label="生日" prop="birthday">
        <el-date-picker
          v-model="contactForm.birthday"
          type="date"
          placeholder="请选择联系人生日"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="家庭住址" prop="address">
        <el-input
          v-model="contactForm.address"
          type="textarea"
          placeholder="请输入联系人家庭住址"
          :rows="3"
        />
      </el-form-item>

      <el-form-item label="默认联系人">
        <el-switch v-model="contactForm.is_default" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, defineEmits, defineProps, defineExpose, watch } from 'vue'
  import { ElMessage, ElForm } from 'element-plus'
  import { customerApi } from '@/api/customer'
  import type { CustomerContact } from '@/types/customer'

  // 定义props和emits
  const props = defineProps({
    customerId: {
      type: [Number, String],
      required: true,
    },
    contactId: {
      type: [Number, String],
      default: '',
    },
    mode: {
      type: String,
      default: 'add', // add or edit
    },
    contactData: {
      type: Object as () => CustomerContact | null,
      default: null,
    },
  })

  const emit = defineEmits(['success', 'cancel'])

  // 表单引用
  const contactFormRef = ref<InstanceType<typeof ElForm> | null>(null)

  // 加载状态
  const submitting = ref(false)
  const loading = ref(false)

  // 表单数据
  const contactForm = reactive<Partial<CustomerContact>>({
    id: undefined,
    cid: undefined,
    name: '',
    mobile: '',
    sex: 0,
    wechat: '',
    email: '',
    qq: '',
    nickname: '',
    department: '',
    position: '',
    birthday: '',
    address: '',
    is_default: 0,
  })

  // 表单验证规则
  const contactRules = reactive({
    name: [
      { required: true, message: '请输入联系人姓名', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
    ],
    mobile: [
      { required: true, message: '请输入联系人手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
    ],
    email: [
      {
        validator: (rule: any, value: string, callback: any) => {
          if (!value || /^[\w.-]+@[\w.-]+\.\w+$/.test(value)) {
            callback()
          } else {
            callback(new Error('请输入正确的邮箱地址'))
          }
        },
        trigger: 'blur',
      },
    ],
  })

  // 初始化表单数据
  const initFormData = async () => {
    // 设置客户ID - 确保转换为数字
    if (props.customerId) {
      contactForm.cid = Number(props.customerId)
      console.log('设置联系人表单的客户ID:', contactForm.cid)
    }

    // 如果是编辑模式，联系人数据应该通过props传递或者从父组件获取
    // 这里暂时不实现，因为编辑时会通过父组件传递完整的联系人数据
  }

  // 提交表单
  const handleSubmit = async () => {
    if (!contactFormRef.value) return

    await contactFormRef.value.validate(async valid => {
      if (!valid) return

      // 再次确保客户ID已设置
      if (!contactForm.cid || contactForm.cid <= 0) {
        if (props.customerId) {
          contactForm.cid = Number(props.customerId)
        } else {
          ElMessage.error('客户ID不能为空')
          return
        }
      }

      submitting.value = true
      try {
        // 创建一个新对象用于提交，将cid改为customer_id
        const submitData: any = { ...contactForm }
        if (submitData.cid) {
          submitData.customer_id = submitData.cid
          delete submitData.cid
        }

        console.log('提交联系人数据:', submitData)

        // 根据模式选择API
        const apiMethod = props.mode === 'add' ? customerApi.addContact : customerApi.editContact

        const response = await apiMethod(submitData)

        if (response && response.code === 0) {
          ElMessage.success(props.mode === 'add' ? '添加联系人成功' : '编辑联系人成功')
          emit('success')
        } else {
          ElMessage.error(
            response?.msg || (props.mode === 'add' ? '添加联系人失败' : '编辑联系人失败')
          )
        }
      } catch (error) {
        console.error(props.mode === 'add' ? '添加联系人失败' : '编辑联系人失败:', error)
        ElMessage.error(props.mode === 'add' ? '添加联系人失败' : '编辑联系人失败')
      } finally {
        submitting.value = false
      }
    })
  }

  // 取消操作
  const handleCancel = () => {
    emit('cancel')
  }

  // 组件初始化
  onMounted(() => {
    initFormData()
  })

  // 监听mode和customerId变化，重置表单数据
  watch(
    () => [props.mode, props.customerId, props.contactData],
    newValues => {
      const [newMode, newCustomerId, newContactData] = newValues

      // 如果切换到新增模式，重置表单数据
      if (newMode === 'add') {
        // 重置表单数据
        contactForm.id = undefined
        contactForm.cid = newCustomerId ? Number(newCustomerId) : undefined
        contactForm.name = ''
        contactForm.mobile = ''
        contactForm.sex = 0
        contactForm.wechat = ''
        contactForm.email = ''
        contactForm.qq = ''
        contactForm.nickname = ''
        contactForm.department = ''
        contactForm.position = ''
        contactForm.birthday = ''
        contactForm.address = ''
        contactForm.is_default = 0
      } else if (newMode === 'edit' && newContactData) {
        // 编辑模式下，填充联系人数据
        Object.assign(contactForm, newContactData)
      }
    },
    { immediate: true }
  )

  // 添加一个方法来手动重置表单
  const resetForm = () => {
    contactForm.id = undefined
    contactForm.cid = props.customerId ? Number(props.customerId) : undefined
    contactForm.name = ''
    contactForm.mobile = ''
    contactForm.sex = 0
    contactForm.wechat = ''
    contactForm.email = ''
    contactForm.qq = ''
    contactForm.nickname = ''
    contactForm.department = ''
    contactForm.position = ''
    contactForm.birthday = ''
    contactForm.address = ''
    contactForm.is_default = 0

    // 重置表单验证状态
    if (contactFormRef.value) {
      contactFormRef.value.resetFields()
    }
  }

  // 暴露方法给父组件调用
  defineExpose({
    handleSubmit,
    handleCancel,
    resetForm,
    submitting,
  })
</script>

<style scoped>
  .contact-form-container {
    padding: 20px;
  }

  .contact-form {
    max-width: 500px;
    margin: 0 auto;
  }
</style>
